package com.tianci.appstore.controller;

import android.content.Intent;
import android.os.RemoteException;
import android.util.Log;

import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.app.framework.app.LiteAppApplication.ContentAppChangedReceiver.ContentAppChangedReceiverListener;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.app.CoocaaApplication.PackageReceiver.InstallUninstallInterface;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedownloader.aidl.IDownloaderServiceListener;
import com.coocaa.x.service.litedownloader.data.DownloadError;
import com.coocaa.x.service.litedownloader.data.DownloadExtra;
import com.coocaa.x.service.litedownloader.data.DownloadTask;
import com.coocaa.x.service.litedownloader.data.ProcessInfo;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreBean;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreBeanList;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreCategory;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.tianci.appstore.R;
import com.tianci.appstore.dataprovider.AppDataProvider;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppStatus;
import com.tianci.appstore.ui.data.SkyCategoryData;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.data.SkyListStatusData;
import com.tianci.appstore.ui.list.cgylist.CgyListDataListener;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.SkyConstants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AppStoreAppListController extends AppStoreBaseController implements
        InstallUninstallInterface, ContentAppChangedReceiverListener {
    private static AppStoreAppListController appListController = null;
    private CgyListDataListener mListener = null;
    private String paresetSort = "";
    private List<AppStoreCategory> categoryList = null;
    private AppStoreCategory childData = null;
    // private String curAppId = "";
    // private Map<String, List<SkyListAppData>> appListMap = null;
    private List<String> keyList = null;
    private static final int MAPCOUNT = 5;
    private Map<String, Map<Integer, List<SkyListAppData>>> appListMap = null;

    public static AppStoreAppListController getInstance() {
        if (null == appListController) {
            appListController = new AppStoreAppListController();
        }
        return appListController;
    }

    public AppStoreAppListController() {
        categoryList = new ArrayList<AppStoreCategory>();
        // appListMap = new HashMap<String, List<SkyListAppData>>();
        keyList = new ArrayList<String>();
        appListMap = new HashMap<String, Map<Integer, List<SkyListAppData>>>();
    }

    public void init() {
        CoocaaApplication.addPackageListener(this);
        LiteAppApplication
                .addContentAppChangedReceiverListener(AppStoreAppListController.this);
        runOnThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                while (true) {
                    try {
                        XServiceManager.getDownloaderService().setListener(downloaderStub);
                        break;
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void setListDataListener(CgyListDataListener listener) {
        mListener = listener;
    }

    // public void setAppId(String appId){
    // curAppId = appId;
    // }

    // 获取应用商城的分类信息
    public List<AppStoreCategory> getCategoryList() {
        return categoryList;
    }

    public void getCategoryListFromWeb() {
        new Thread() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    LogUtils.d("li", "getCategoryListFromWeb------------");
                    categoryList = CoocaaApplication.getCoocaaWebService().getAppStoreService().getAppCategory();
                } catch (AppStoreException e) {
                    // TODO Auto-generated catch block
                    LogAPIForAppStore
                            .reportInterfaceError("获取应用的分类列表", Android.throwable2String(e));
                    e.printStackTrace();
                }
            }

        }.start();
    }

    public int getCategoryCount(String CategoryTypeId) {
        if (categoryList != null) {
            for (int i = 0; i < categoryList.size(); i++) {
                AppStoreCategory pageData = categoryList.get(i);
                for (int j = 0; j < pageData.subSorts.size(); j++) {
                    if (CategoryTypeId.equals(pageData.subSorts.get(j).sortId)) {
                        LogUtils.d("applit", "getCategoryCount---" + pageData.subSorts.get(j).appCount);
                        return Integer.parseInt(pageData.subSorts.get(j).appCount);
                    }
                }
            }
        }
        return 0;
    }

    // 获取某分类app的总个数
    public void get8PageAppList(final String CategoryTypeId, final int pageindex_8,
                                final int curIndex) {

        new Thread() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                // killTimer(TimerType.APP_LIST);
                // startTimer(TimerType.APP_LIST, applistTimeoutHandler,CategoryTypeId);
                List<AppStoreBean> list = getAppListFromWeb(CategoryTypeId, pageindex_8,
                        8 * SkyConstants.PAGECOUNT);

                if (null == list || list.size() == 0) {
                    return;
                }
                // killTimer(TimerType.APP_LIST);
                List<SkyListAppData> appList = new ArrayList<SkyListAppData>();
                for (int i = 0; i < list.size(); i++) {
                    AppStoreBean bean = list.get(i);
                    SkyListStatusData data = new SkyListStatusData(ListType.CGY_APP_LIST);
                    data.setId(bean.id);
                    data.setIconUrl(bean.lmg);
                    data.setPkgName(bean.packagename);
                    data.setVersionName(bean.version);
                    data.setShowInfo(getString(R.string.downloaded_count)
                            + String.valueOf(bean.downloads));
                    data.setTitle(bean.name);
                    data.setExtra(bean.superscript); // 第一个角标
                    AppStatus status = AppStatus.NOT_DOWNLOADED;
                    status = AppDataProvider.getInstance().getAppStatus(bean.packagename,
                            bean.version);
                    LogUtils.d("li", "MSG_GETAPPLIST---" + bean.name + " " + status.toString());
                    data.setStatus(status);
                    appList.add(data);
                }
                LogUtils.d("applist", "MSG_GETAPPLIST---" + appList.size());
                putAppListMap(CategoryTypeId, pageindex_8, appList);
                if (curIndex > 0) {
                    getAppListFromMap(CategoryTypeId, curIndex, 12);
                }
            }

        }.start();
    }

    public void putAppListMap(String categoryId, int pageindex_8, List<SkyListAppData> appList) {
        Map<Integer, List<SkyListAppData>> list = new HashMap<Integer, List<SkyListAppData>>();
        if (appListMap != null && keyList != null) {
            if (appListMap.containsKey(categoryId)) {
                if (appListMap.get(categoryId).containsKey(pageindex_8)) {
                    appListMap.get(categoryId).remove(pageindex_8);
                    appListMap.get(categoryId).put(pageindex_8, appList);
                } else {
                    appListMap.get(categoryId).put(pageindex_8, appList);
                }
            } else if (appListMap.size() < MAPCOUNT) {
                keyList.add(categoryId);
                list.put(pageindex_8, appList);
                appListMap.put(categoryId, list);
            } else if (appListMap.size() >= MAPCOUNT) {
                appListMap.remove(keyList.get(0));
                keyList.remove(0);
                list.put(pageindex_8, appList);
                appListMap.put(categoryId, list);
                keyList.add(categoryId);
            }
        }
    }

    public boolean getAppListFromMap(String categoryId, int curindex, int pagecount) {
        List<SkyListAppData> appList = new ArrayList<SkyListAppData>();
        boolean isNeedDown = true;
        if ((curindex % 8) == 3) {
            if (appListMap.containsKey(categoryId)) {
                if (appListMap.get(categoryId).containsKey((curindex / 8) + 1)) {
                    LogUtils.d("applist", "not need  download data for next page ---index:"
                            + (curindex / 8) + 1);
                    isNeedDown = false;
                }
            }
            if (isNeedDown) {
                LogUtils.d("applist", "download data for next page ---index:" + (curindex / 8) + 1);
                get8PageAppList(categoryId, (curindex / 8) + 1, 0);
            }
        }
        if (appListMap.containsKey(categoryId)) {
            Map<Integer, List<SkyListAppData>> map = new HashMap<Integer, List<SkyListAppData>>();
            map = appListMap.get(categoryId);
            int index = 0;
            int pageIndex = 0;
            if (curindex % 8 == 0) {
                index = (curindex / 8);
                pageIndex = 8;
            } else {
                index = (curindex / 8) + 1;
                pageIndex = curindex % 8;
            }
            if (map.containsKey(index)) {
                List<SkyListAppData> list = map.get(index);
                int count = list.size();
                if (count <= pageIndex * pagecount) {
                    if ((pageIndex - 1) * pagecount >= 0 && count > (pageIndex - 1) * pagecount)
                        appList = list.subList((pageIndex - 1) * pagecount, count);
                } else {
                    appList = list.subList((pageIndex - 1) * pagecount, pageIndex * pagecount);
                }
                LogUtils.d("applist", "get data from  map !!!!!  pageIndex:" + pageIndex + " "
                        + categoryId + " " + appList.size());
                mListener.onAppPageLoaded(categoryId, curindex, appList);
                if (appList != null && appList.size() > 0) {
                    for (int i = 0; i < appList.size(); i++) {
                        SkyListAppData app = appList.get(i);
                        AppStatus status = AppStatus.NOT_DOWNLOADED;
                        status = AppDataProvider.getInstance().getAppStatus(app.getPkgName(),
                                app.getVersionName());
                        refreshAppList(app.getPkgName(), status);
                    }
                }
                return true;
            }
        }
        return false;
    }

    // 获取某分类的列表
    public void getAppList(final String CategoryTypeId, final int curindex, final int pagecount) {
        // 后续做法不要冲网络拿数据，直接在缓存中拿。
        if (getAppListFromMap(CategoryTypeId, curindex, pagecount)) {
            return;
        }
        LogUtils.d("applist", "get data from  web !!!!!  pageIndex:" + curindex);
        int index = 0;
        if (curindex % 8 == 0) {
            index = curindex / 8;
        } else {
            index = (curindex / 8) + 1;
        }
        get8PageAppList(CategoryTypeId, index, curindex);

    }

    // 获取app列表
    public synchronized List<AppStoreBean> getAppListFromWeb(final String CategoryTypeId,
                                                             int pageindex, int pagecount) {
        LogUtils.d("li", "getAppListFromWeb---" + CategoryTypeId + " " + pageindex);
        List<AppStoreBean> list = null;
        try {
            AppStoreBeanList appStoreBean = CoocaaApplication.getCoocaaWebService().getAppStoreService().getAppList(
                    CategoryTypeId, pageindex, pagecount);
            list = appStoreBean.data;
        } catch (AppStoreException e) {
            LogAPIForAppStore.reportInterfaceError("根据分类id，页数获取应用列表", Android.throwable2String(e));
            e.printStackTrace();
            LogUtils.d("lqw", "AppStoreException:" + e);
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    mListener.onAppPageLoaded(CategoryTypeId, -1, null);
                    TipToast.getInstance(mContext).showTipToast("获取后台数据异常！");
                }
            });

        }
        return list;
    }

    public long getLongConfig(String key) {
        try {
            return XServiceManager.getLiteConfigService().getLongValue(key, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public void saveConfig(String sortId) {
        AppStoreCategory data = getAppStoreCategory(sortId);
        if (data != null) {
            String updateTime = data.updateTime;
            try {
                XServiceManager.getLiteConfigService().saveStringConfig(sortId, updateTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 是否显示脚标
    public int showSortAppCount(String sortId) {
        if (categoryList != null && categoryList.size() > 0) {
            for (int i = 0; i < categoryList.size(); i++) {
                AppStoreCategory pageData = categoryList.get(i);
                if (pageData == null || pageData.subSorts == null || pageData.subSorts.size() < 1) {
                    return 0;
                }
                for (int j = 0; j < pageData.subSorts.size(); j++) {
                    if (sortId.equals(pageData.subSorts.get(j).sortId)) {
                        int isShowCount = Integer.parseInt(pageData.subSorts.get(j).showCount);
                        long curData = Long.parseLong(pageData.subSorts.get(j).updateTime);
                        long savedData = getLongConfig(sortId);
                        LogUtils.d("count", "showSortAppCount---" + isShowCount + " " + curData + " "
                                + savedData);
                        if (isShowCount == 1) {
                            if (curData > savedData) {
                                // int count = Integer.parseInt(pageData.subSorts.get(j).appCount);
                                if (pageData.subSorts.get(j).supCount == null) {
                                    LogUtils.d("count", "showSortAppCount---count is null");
                                    return 0;
                                }
                                int count = Integer.parseInt(pageData.subSorts.get(j).supCount);
                                LogUtils.d("count", "showSortAppCount---count:" + count);
                                return count;
                            } else {
                                return 0;
                            }
                        } else {
                            return 0;
                        }
                    }
                }
            }
        }
        return 0;
    }

    public AppStoreCategory getAppStoreCategory(String sortId) {
        if (categoryList != null && categoryList.size() > 0) {
            for (int i = 0; i < categoryList.size(); i++) {
                AppStoreCategory pageData = categoryList.get(i);
                LogUtils.d("count", "getAppStoreCategory--" + pageData.sortId);
                for (int j = 0; j < pageData.subSorts.size(); j++) {
                    if (sortId.equals(pageData.subSorts.get(j).sortId)) {
                        return pageData.subSorts.get(j);
                    }
                }
            }
        }
        return null;
    }

    public void getRelationCategory(String sortId) {
        AppStoreCategory curSort = null;
        if (categoryList != null && categoryList.size() > 0) {
            for (int i = 0; i < categoryList.size(); i++) {
                AppStoreCategory pageData = categoryList.get(i);
                String sortTem = pageData.sortName;
                for (int j = 0; j < pageData.subSorts.size(); j++) {
                    if (sortId.equals(pageData.subSorts.get(j).sortId)) {
                        paresetSort = sortTem;
                        childData = pageData;
                        int sign = Integer.parseInt(pageData.subSorts.get(j).single);
                        if (sign == 1) {
                            curSort = pageData.subSorts.get(j);
                        }
                        break;
                    }
                }
            }
        } else {
            getCategoryListFromWeb();
        }

        // // TODO Auto-generated method stub
        List<SkyCategoryData> categoryDataList = new ArrayList<SkyCategoryData>();
        String parentTitle = paresetSort;
        LogUtils.d("list", "(curSort != null):" + (curSort != null));
        if (curSort != null) {
            SkyCategoryData data = new SkyCategoryData();
            data.id = curSort.sortId;
            data.name = curSort.sortName;
            data.totalCount = Integer.parseInt(curSort.appCount);
            categoryDataList.add(data);
            mListener.onCategoryLoaded(parentTitle, categoryDataList);
            return;
        }
        if (childData != null && childData.subSorts != null && childData.subSorts.size() > 0) {
            for (int i = 0; i < childData.subSorts.size(); i++) {
                SkyCategoryData data = new SkyCategoryData();
                data.id = childData.subSorts.get(i).sortId;
                data.name = childData.subSorts.get(i).sortName;
                data.totalCount = Integer.parseInt(childData.subSorts.get(i).appCount);
                LogUtils.d("li", "getRelationCategory--run-" + data.id + " " + data.totalCount);
                categoryDataList.add(data);
            }
        } else {
            getCategoryListFromWeb();
        }
        LogUtils.d("li", "MSG_GETCATEGORYLIST----" + categoryDataList.size());
        mListener.onCategoryLoaded(parentTitle, categoryDataList);
        return;
    }

    public void refreshAppList(String pkg, AppStatus appStatus) {
        if (mListener != null && !pkg.equals("")) {
            LogUtils.d("intent", "refreshAppList--更新状态--" + pkg + " " + appStatus);
            mListener.onAppStatusChanged(pkg, appStatus);
        }
    }

    @Override
    public void destroy() {
        CoocaaApplication.removePackageListener(this);
        try {
            XServiceManager.getDownloaderService().clearListener(downloaderStub);
        } catch (Exception e) {
            e.printStackTrace();
        }
        LiteAppApplication.removeContentAppChangedReceiverListener(this);
        mListener = new CgyListDataListener(){
            @Override
            public void onCategoryLoaded(String parentTitle, List<SkyCategoryData> cgyList) {

            }

            @Override
            public void onAppPageLoaded(String cgyId, int pageIndex, List<SkyListAppData> appList) {

            }

            @Override
            public void onAppStatusChanged(String appId, AppStatus status) {

            }
        };
    }

    private IDownloaderServiceListener.Stub downloaderStub = new IDownloaderServiceListener.Stub() {

        @Override
        public void onReady(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
            refreshAppList(extra.pkgname, AppStatus.WAITING);
        }

        @Override
        public void onPrepare(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStart(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
            refreshAppList(extra.pkgname, AppStatus.DOWNLOADING);
        }

        @Override
        public void onStop(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
            refreshAppList(extra.pkgname, AppStatus.DOWNLOAD_PAUSED);
        }

        @Override
        public void onProcessInfo(DownloadTask task, ProcessInfo info) throws RemoteException {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFinish(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
            refreshAppList(extra.pkgname, AppStatus.DOWNLOADED);
        }

        @Override
        public void onError(DownloadTask task, DownloadError error) throws RemoteException {
            // TODO Auto-generated method stub

        }

        @Override
        public void onDelete(DownloadTask task) throws RemoteException {
            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
            boolean isInstalled = XServiceManager.getLitePMService().isInstalled(extra.pkgname);
            LogUtils.d("intent", "onDelete--isInstalled:" + isInstalled);
            if (!isInstalled)
                refreshAppList(extra.pkgname, AppStatus.NOT_DOWNLOADED);
        }
    };

    @Override
    public void installEvent(Intent i) {
        // TODO Auto-generated method stub
        LogUtils.d("intent", "installEvent--pkg:" + i.getData().getSchemeSpecificPart());
        String pkg = i.getData().getSchemeSpecificPart();
        refreshAppList(pkg, AppStatus.INSTALLED);
    }

    @Override
    public void uninstallEvent(Intent i) {
        // TODO Auto-generated method stub
        LogUtils.d("intent", "uninstallEvent--pkg:" + i.getData().getSchemeSpecificPart());
        String pkg = i.getData().getSchemeSpecificPart();
        refreshAppList(pkg, AppStatus.NOT_DOWNLOADED);
    }

    @Override
    public void onAction(Intent i) {
        String[] pkgArray = null;
        if (i != null)
            pkgArray = i.getStringArrayExtra("extra");
        if (pkgArray != null && pkgArray.length > 0) {
            LogUtils.d("test", "onAction list pkg:" + pkgArray.length);
            for (String pkg : pkgArray) {
                if (pkg != null && !pkg.equals("")) {
                    AppStatus status = AppStatus.NOT_DOWNLOADED;
                    status = AppDataProvider.getInstance().isAppInstalled(pkg);
                    refreshAppList(pkg, status);
                }
            }
        }
    }

}
